package com.yyfax.ph.personal.authority.register;


import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.IView;
import com.yyfax.infrastructure.mvp.PresenterFactory;
import com.yyfax.infrastructure.secure.RSA;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.common.GlobalVariableConfig;
import com.yyfax.ph.personal.authority.RSAPresenter;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class RegisterPresenter extends RSAPresenter<RegisterModel, RegisterPresenter.View> {
	private static final String TAG = RegisterPresenter.class.getSimpleName();
	private View mView;

	public static class Generator implements PresenterFactory<RegisterPresenter> {
		@Override
		public RegisterPresenter create() {
			return new RegisterPresenter();
		}
	}

	@Override
	public void attach(View view) {
		mView = view;
		mModel = new RegisterModel();
		EventAgent.register(this);
	}

	@Override
	public void detach() {
		mView = null;
		mModel = null;
		EventAgent.unregister(this);
	}

	public interface View extends IView {
		RegisterModel.Params getRegisterParams();

		void registerSuccess(String type);

		void registerFailure(String tips);
	}

	@Override
	public Object getRSAParams(Object params, int functionalCode) {
		RegisterModel.Params register = (RegisterModel.Params) params;
		String keyRSA = GlobalVariableConfig.getKeyRSA();
		register.password = RSA.encryptByPublicKey(register.password, keyRSA);
		register.loginName = RSA.encryptByPublicKey(register.loginName, keyRSA);
		return register;
	}

	public void register() {
		execute(mView.getRegisterParams());
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void registerResult(RegisterModel.RegisterResult registerResult) {
		StatService.onEventFirstKeyAttribute(YJPH.getInstance(), StatIDSet.EVENT_ID_E038, registerResult.getStatus());
		if (isResponseSuccess(registerResult)) {
			mView.registerSuccess(registerResult.getContent().type);
		} else if (isResponseWarning(registerResult)) {
			if (registerResult.getContent() != null && "10008".equals(registerResult.getContent().code)) {//用于清空验证码
				mView.registerFailure("验证码错误");
			} else {
				mView.registerFailure(registerResult.getMsg());
			}
		} else {
			mView.registerFailure(registerResult.getMsg());
		}
	}

}
